$(document).ready(function() {
    console.log('初始化主页功能');

    // 天气监控相关变量
    let weatherChart = null;
    const weatherData = {
        dates: [],
        temperatures: [],
        humidity: []
    };

    // 内存监控相关变量
    let memoryChart = null;
    let processChart = null;
    const memoryData = {
        timestamps: [],
        usage: []
    };

    // 初始化事件绑定
    initEventHandlers();

    function initEventHandlers() {
        console.log('初始化主页事件绑定');

        // 天气按钮点击事件
        $('.weather-btn').on('click', function() {
            console.log('天气按钮点击');
            const $btn = $(this);
            const $container = $('.weather-chart-container');
            
            if ($container.hasClass('show')) {
                $container.removeClass('show');
                $btn.removeClass('active');
            } else {
                $container.addClass('show');
                $btn.addClass('active');
                
                if (!weatherChart) {
                    initWeatherChart();
                }
            }
        });

        // 内存监控按钮点击事件
        $('.monitor-btn').on('click', function() {
            console.log('内存监控按钮点击');
            const $btn = $(this);
            const $container = $('.memory-chart-container');
            
            if ($container.hasClass('show')) {
                $container.removeClass('show');
                $btn.removeClass('active');
            } else {
                $container.addClass('show');
                $btn.addClass('active');
                
                if (!memoryChart || !processChart) {
                    initMemoryCharts();
                }
            }
        });

        // 图表关闭按钮点击事件
        $('.chart-close').on('click', function() {
            console.log('图表关闭按钮点击');
            const $container = $(this).closest('.chart-container');
            const $btn = $container.hasClass('weather-chart-container') ? 
                        $('.weather-btn') : $('.monitor-btn');
            
            $container.removeClass('show');
            $btn.removeClass('active');
        });

        // 导出按钮点击事件
        $('.export-btn').on('click', function() {
            console.log('导出按钮点击');
            const chart = weatherChart;
            if (chart) {
                const url = chart.getDataURL();
                const link = document.createElement('a');
                link.download = '天气数据图表.png';
                link.href = url;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        });

        // PDF预览按钮点击事件
        $('.preview-pdf-btn').on('click', function() {
            console.log('PDF预览按钮点击');
            generatePDF();
        });

        // PDF预览关闭按钮点击事件
        $('.pdf-close-btn').on('click', function() {
            console.log('PDF预览关闭按钮点击');
            $('.pdf-preview-overlay').fadeOut(300);
        });

        // 日期选择器变更事件
        $('#weatherMonth').on('change', function() {
            console.log('日期选择变更');
            updateWeatherData($(this).val());
        });
    }

    // 初始化天气图表
    function initWeatherChart() {
        console.log('初始化天气图表');
        const chartDom = document.getElementById('weatherChart');
        weatherChart = echarts.init(chartDom);
        
        const option = {
            title: {
                text: '珠海天气趋势'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['温度', '湿度']
            },
            xAxis: {
                type: 'category',
                data: weatherData.dates
            },
            yAxis: [
                {
                    type: 'value',
                    name: '温度(°C)'
                },
                {
                    type: 'value',
                    name: '湿度(%)',
                    min: 0,
                    max: 100
                }
            ],
            series: [
                {
                    name: '温度',
                    type: 'line',
                    data: weatherData.temperatures
                },
                {
                    name: '湿度',
                    type: 'line',
                    yAxisIndex: 1,
                    data: weatherData.humidity
                }
            ]
        };
        
        weatherChart.setOption(option);
    }

    // 初始化内存监控图表
    function initMemoryCharts() {
        console.log('初始化内存监控图表');
        
        // 内存使用趋势图表
        const trendDom = document.getElementById('memoryTrendChart');
        memoryChart = echarts.init(trendDom);
        
        const trendOption = {
            title: {
                text: '内存使用趋势'
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: memoryData.timestamps
            },
            yAxis: {
                type: 'value',
                name: '内存使用(MB)'
            },
            series: [
                {
                    type: 'line',
                    data: memoryData.usage,
                    areaStyle: {}
                }
            ]
        };
        
        memoryChart.setOption(trendOption);
        
        // 进程内存占用图表
        const processDom = document.getElementById('processChart');
        processChart = echarts.init(processDom);
        
        const processOption = {
            title: {
                text: '进程内存占用'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}MB ({d}%)'
            },
            series: [
                {
                    type: 'pie',
                    radius: '60%',
                    data: [
                        { value: 335, name: '系统进程' },
                        { value: 234, name: '用户进程' },
                        { value: 158, name: '服务进程' },
                        { value: 135, name: '其他' }
                    ]
                }
            ]
        };
        
        processChart.setOption(processOption);
    }

    // 更新天气数据
    function updateWeatherData(month) {
        console.log('更新天气数据:', month);
        // 这里应该调用后端API获取数据
        // 目前使用模拟数据
        weatherData.dates = ['1日', '2日', '3日', '4日', '5日'];
        weatherData.temperatures = [20, 22, 25, 23, 21];
        weatherData.humidity = [65, 70, 75, 68, 72];
        
        if (weatherChart) {
            weatherChart.setOption({
                xAxis: {
                    data: weatherData.dates
                },
                series: [
                    {
                        data: weatherData.temperatures
                    },
                    {
                        data: weatherData.humidity
                    }
                ]
            });
        }
    }

    // 生成PDF预览
    function generatePDF() {
        console.log('生成PDF预览');
        if (!weatherChart) return;
        
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF();
        
        pdf.text('珠海天气数据报告', 20, 20);
        
        const imgData = weatherChart.getDataURL({
            pixelRatio: 2,
            backgroundColor: '#fff'
        });
        
        pdf.addImage(imgData, 'PNG', 15, 40, 180, 100);
        
        const pdfData = pdf.output('datauristring');
        $('#pdfViewer').attr('src', pdfData);
        $('.pdf-preview-overlay').fadeIn(300);
    }

    // 窗口大小改变时调整图表大小
    $(window).on('resize', function() {
        if (weatherChart) {
            weatherChart.resize();
        }
        if (memoryChart) {
            memoryChart.resize();
        }
        if (processChart) {
            processChart.resize();
        }
    });
}); 